import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { ElMessage } from 'element-plus'
const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login/index.vue'),
  }, {
    path: '/',
    component: () => import('../views/layout/index.vue'),
    redirect: { name: "Index" },
    children: [
      {
        path: "/main",
        name: "Index",
        component: () => import('../views/main/index.vue')
      },
      {
        path: '/share',
        name: 'Share',
        component: () => import('../views/share/index.vue')
      }
    ]
  },
  {
    path: '/shareurl',
    component: () => import('../views/fenxiang/index.vue')
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})


// 前置路由
router.beforeEach(async (to, from, next) => {
  let userInfo = localStorage.getItem('user') as string || JSON.stringify({ user: {}, token: '' })
  userInfo = JSON.parse(userInfo)
  const token = (userInfo as unknown as any).token || ''
  const user = (userInfo as unknown as any).user || {}
  if (token && user) {
    // 防止重复登录
    if (to.path === '/login') {
      ElMessage({
        message: '请勿重复登录!',
        type: "warning"
      })
      return next({ name: from.name ? from.name : 'Index' })
    }
    next()
  } else {
    if (to.path === '/login' || to.path === '/shareurl') {
      return next()
    }
    // 未登录
    ElMessage({
      message: '请先登录!',
      type: "warning"
    })
    next({ name: 'Login' })
  }
})

export default router
